package com.itwn.portal.config;

import com.itwn.portal.interceptor.JwtInterceptor;
import com.itwn.portal.model.vo.UrlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableConfigurationProperties(UrlProperties.class)
public class BookMvcConfig implements WebMvcConfigurer {

    @Value("${portal.allowed-origins}")
    private String[] allowedOrigins;

    //图片的访问地址
    @Value("${portal.image-path}")
    private String imagePath;

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Autowired
    private UrlProperties urlProperties;

    /**
     * 拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**") // 拦截的资源
                .excludePathPatterns(urlProperties.getWhiteNames());
    }

    /**
     * 允许所有类型的请求来自 http://localhost:9000 服务器
     * 并且允许的请求类型包括GET、POST、PUT、DELETE、OPTIONS
     * 允许与凭据一起发送请求，不然不能使用Cookie，导致会话不能使用
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  //允许所有访问地址
                .allowedOrigins(allowedOrigins) //允许哪些服务器地址
                .allowedMethods("*")   //允许的请求类型
                .allowedHeaders("*")   //允许所有的请求头
                .allowCredentials(true)  //允许与凭据一起发送请求，Cookie可以跨域
                .exposedHeaders("*");   //允许返回的头信息
    }

    /**
     * 配置资源的访问地址
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 访问： http://localhost:8080/images/1a4e56fa8cf44be095612c9e9c81cc85.jpg
        // 映射到： C:/class/gzclass13/book-mall/1a4e56fa8cf44be095612c9e9c81cc85.jpg
        registry.addResourceHandler("/images/**").addResourceLocations(imagePath);
    }
}